package com.mantru.iotpot.Util

class TimeUtil {
    companion object {
        /**
         * 将秒数转换为指定的时间格式
         * @param seconds 秒数
         * @param format 格式字符串，例如 "mm:ss"、"hh:mm:ss"、"yyyy:MM:dd hh:mm:ss"
         * @return 格式化后的时间字符串
         */
        fun formatDuration(seconds: Int, format: String): String {
            val formattedParts = format.split(':')
            val units = formattedParts.map { it.first().toString() }.distinct()

            val unitSeconds = mapOf(
                "d" to 86400,
                "h" to 3600,
                "m" to 60,
                "s" to 1
            )

            val sortedUnits = units.sortedByDescending { unitSeconds[it] ?: 0 }

            var remainder = seconds
            val timeComponents = mutableMapOf<String, Int>()

            for (unit in sortedUnits) {
                val secondsPerUnit = unitSeconds[unit] ?: continue
                val value = remainder / secondsPerUnit
                timeComponents[unit] = value
                remainder %= secondsPerUnit
            }

            val formattedTime = formattedParts.joinToString(":") { part ->
                val unit = part.first().toString()
                val value = timeComponents[unit] ?: 0
                String.format("%0${part.length}d", value)
            }

            return formattedTime
        }
    }
}